<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="区服名称" prop="regionName">
        <el-input v-model="queryParams.regionName" placeholder="请输入区服名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="选择状态" @change="handleSelectChange2" style="width: 100%;">
          <el-option v-for="option in zhuangtaiList" :key="option.regionId" :value="option.regionId"
            :label="option.regionName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['server:task:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="区服名称" align="center" prop="regionName" />
      <el-table-column label="资历" align="center" prop="score" />
      <el-table-column label="类型" align="center" prop="teamType" />
      <el-table-column label="原价" align="center" prop="price" />
      <el-table-column label="折扣价" align="center" prop="discountPrice" />
      <el-table-column label="报名人数" align="center" prop="applyPeopleCount" />
      <el-table-column label="介绍" align="center" prop="introduce" />
      <el-table-column label="状态" align="center" prop="stateName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" width="200" align="center" class-name="small-padding">
        <template slot-scope="scope">
          <el-button v-if="getVisibleButtons(scope.row).includes('edit')" size="mini" type="text"
            @click="handleUpdate(scope.row)" v-hasPermi="['server:task:edit']">编辑</el-button>
          <el-button v-if="getVisibleButtons(scope.row).includes('delete')" size="mini" type="text"
            @click="handleDelete(scope.row)" v-hasPermi="['server:task:remove']">删除</el-button>
          <el-button v-if="getVisibleButtons(scope.row).includes('publish')" size="mini" type="text"
            @click="handRelease(scope.row, 1)" v-hasPermi="['server:task:changeState']">发布</el-button>
          <el-button v-if="getVisibleButtons(scope.row).includes('complete')" size="mini" type="text"
            @click="handRelease(scope.row, 2)" v-hasPermi="['server:task:changeState']">完成</el-button>
          <el-button v-if="getVisibleButtons(scope.row).includes('begin')" size="mini" type="text"
            @click="handRelease(scope.row, 3)" v-hasPermi="['server:task:changeState']">开始</el-button>
          <el-button v-if="getVisibleButtons(scope.row).includes('details')" size="mini" type="text"
            @click="getTask(scope.row.taskId,scope.row.taskName)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改区服任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="区服名称" prop="regionName">
          <el-select v-model="qufuId" placeholder="请选择区服" @change="handleSelectChange" style="width: 100%;">
            <el-option v-for="option in qufu" :key="option.regionId" :value="option.regionId"
              :label="option.regionName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资历" prop="score">
          <el-input v-model.number="form.score" placeholder="请输入数字" />
        </el-form-item>
        <el-form-item label="类型" prop="teamType">
          <el-input v-model="form.teamType" placeholder="自动获取" readonly />
        </el-form-item>

        <el-form-item label="原价" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="折扣价" prop="discountPrice">
          <el-input v-model="form.discountPrice" placeholder="请输入折扣价" />
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="账号信息" :visible.sync="dialogTableVisible" :close-on-click-modal="false">
      <el-col :span="1.5" style="margin-bottom: 20px;">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['server:task:export']">导出</el-button>
      </el-col>
      <el-table :data="appUserAccountList">
        <el-table-column prop="gameId" label="游戏ID"></el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column prop="server" label="服务器"></el-table-column>
        <el-table-column prop="account" label="账号"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, changeState } from "@/api/server/task";
import { listRegion } from "@/api/server/region";

export default {
  name: "Task",
  data() {
    return {
      qufu: [],
      qufuId: '',
      zhuangtaiList: [
        { regionId: 0, regionName: '草稿' },
        { regionId: 1, regionName: '发布' },
        { regionId: 2, regionName: '完成' },
        { regionId: 3, regionName: '开始' }
      ],
      // 遮罩层
      loading: true,
      // 账号信息详情弹窗
      dialogTableVisible: false,
      gridData: [],
      taskId: '',
      taskName:'',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区服任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        regionId: null,
        regionName: null,
        score: null,
        teamType: null,
        price: null,
        introduce: null,
        state: null,
      },
      // 表单参数
      form: {},
      appUserAccountList: [],
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        regionId: [
          { required: true, message: "区服id不能为空", trigger: "blur" }
        ],
        regionName: [
          { required: true, message: "区服名称不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "资历不能为空", trigger: "blur" }
        ],
        teamType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        discountPrice: [
          { required: true, message: "折扣价格不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],

        delFlag: [
          { required: true, message: "删除标识不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询区服列表 */
    getListqufu() {
      this.loading = true;
      listRegion(this.queryParams).then(response => {
        // console.log(response)
        this.qufu = response.rows;
        this.loading = false;
      });
    },
    // 下拉框发生选择时
    handleSelectChange() {
      const selectedOption = this.qufu.find(option => option.regionId === this.qufuId);
      if (selectedOption) {
        this.form.regionName = selectedOption.regionName;
        this.form.regionId = this.qufuId;
      }
    },
    // 选择状态
    handleSelectChange2(state) {
      this.queryParams.state = state;
    },

    /** 查询区服任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        const stateMap = {
          0: "草稿",
          1: "发布",
          2: "完成",
          3: "开始"
        };
        response.rows.forEach(res => {
          res.state = stateMap[res.state] || res.state;
        });

        this.taskList = response.rows;
        // console.log(this.taskList)
        this.total = Number(response.total);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskName: null,
        regionId: null,
        regionName: null,
        score: null,
        teamType: '成就团',
        price: null,
        discountPrice: null,
        introduce: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getListqufu();
      const SregionId = this.form.regionId;
      const SregionName = this.form.regionName;
      this.reset();
      this.form.regionId = SregionId;
      this.form.regionName = SregionName;
      this.open = true;
      this.title = "添加区服任务";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getListqufu();
      this.reset();
      const taskId = row.taskId || this.ids
      this.getTask(taskId)
      this.dialogTableVisible = false;
      this.open = true;
      this.title = "修改区服任务";
    },

    // 查看详情
    getTask(taskId,taskName) {
      this.dialogTableVisible = true;
      this.taskId = taskId;
      this.taskName = taskName;
      getTask(taskId).then(response => {
        this.form = response.data;
        this.appUserAccountList = response.data.appUserAccountList;
      });
    },

    getVisibleButtons(row) {
      if (row.state == "草稿") {
        return ['edit', 'delete', 'publish'];
      } else if (row.state == "发布") {
        return ['begin', 'details'];
      } else if (row.state == "开始") {
        return ['complete', 'details'];
      } else if (row.state == "完成") {
        return ['details'];
      }
      return [];
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除"' + row.taskName + '"的数据项？').then(function () {
      }).then(() => {
        delTask(row.taskId).then(res => {
          if (res.code == 200) {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }
        })
      }).catch(() => { });
    },

    // 发布按钮操作
    handRelease(row, state) {
      // console.log(state)
      let tips = '';
      if (state == 1) {
        tips = '发布'
      } else if (state == 2) {
        tips = '完成'
      } else if (state == 3) {
        tips = '开始'
      }
      let _this = this;
      this.$modal.confirm('是否确认' + tips + '[ ' + row.taskName + ']').then(function () {
        changeState({
          state: state,
          taskId: row.taskId
        }).then(res => {
          // console.log(res)
          if (res.code == 200) {
            _this.$modal.msgSuccess(res.msg);
            _this.getList();
          }

        })
      }).then(() => {

      }).catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('server/task/export', {
        taskId: this.taskId,
      }, `${this.taskName}.xlsx`)
    }

  }
};
</script>
